package com.platform.controller.web;

import com.alibaba.fastjson2.JSONObject;
import com.platform.common.annotation.Log;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.enums.BusinessType;
import com.platform.common.enums.ResultEnum;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.http.HttpUtils;
import com.platform.framework.web.service.web.WebUserLoginService;
import com.platform.system.domain.dto.device.WebUserInfoDto;
import com.platform.system.domain.vo.device.WebUserInfoVo;
import com.platform.system.domain.vo.device.WxLoginInfoAnalyze;
import com.platform.system.domain.vo.device.WxLoginInfoVo;
import com.platform.system.service.ISysWebUserInfoService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Huangkai
 */
@Slf4j
@RestController
@RequestMapping("/web/user")
public class UserInfoController {

    @Value("${spring.tencent.weChat.APPID}")
    private String APPID;

    @Value("${spring.tencent.weChat.APPSECRET}")
    private String APPSECRET;

    @Autowired
    WebUserLoginService webUserLoginService;

    @Resource
    ISysWebUserInfoService webUserInfoService;


    /**
     * 获取用户信息
     */
    @Log(title = "获取用户信息", businessType = BusinessType.OTHER)
    @PostMapping("/selectWebUser")
    public AjaxResult selectWebUser(@RequestBody @Validated WebUserInfoVo webUserVo) {
        WebUserInfoDto webUserInfoDto = webUserInfoService.selectWebUser(webUserVo);
        if(webUserInfoDto == null){
            throw new BusinessException(ResultEnum.USER_NOT_EXIST);
        }
        return AjaxResult.success(webUserInfoDto);
    }

    /**
     * 登陆
     */
    @Log(title = "登陆", businessType = BusinessType.OTHER)
    @PostMapping("/login")
    public AjaxResult webLogin(@RequestBody @Validated WebUserInfoVo webUserVo) {
        return webUserLoginService.webLogin(webUserVo);
    }

    /**
     * 修改用户信息
     */
    @Log(title = "修改用户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateWebUser")
    public AjaxResult updateWebUser(@RequestBody @Validated WebUserInfoVo webUserVo) {
        return webUserInfoService.updateWebUser(webUserVo);
    }

    /**
     * 获取验证码
     */
    @Log(title = "获取验证码", businessType = BusinessType.OTHER)
    @PostMapping("/getCode")
    public AjaxResult getCode(@RequestBody @Validated WebUserInfoVo webUserVo) {
        return webUserLoginService.getCode(webUserVo);
    }
    @ApiOperation(value = "获取openId", notes = "获取openId")
    @PostMapping(value = "/getOpenId")
    public AjaxResult getOpenId(@RequestBody WebUserInfoVo webUserInfoVo) {
        try{
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
            String replaceUrl = url.replace("{0}", APPID).replace("{1}", APPSECRET).replace("{2}", webUserInfoVo.getCode());
            String result = HttpUtils.sendGet(replaceUrl);
            log.info("结果{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.containsKey("openid")){
                Map<String, String> returnResult = new HashMap<>(2);
                returnResult.put("openId", jsonObject.getString("openid"));
                returnResult.put("sessionKey", jsonObject.getString("session_key"));
                return AjaxResult.success(returnResult);
            }
            return AjaxResult.error("获取失败");

        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @PostMapping(value = "/wxUserInfo")
    public AjaxResult wxUserInfo(@RequestBody WxLoginInfoVo wxLoginInfoVo) {
        log.info("微信用户登录参数{}", JSONObject.toJSONString(wxLoginInfoVo));
        String userInfoJson = decryptUserInfo(wxLoginInfoVo.getEncryptedData(),
                "utf-8", wxLoginInfoVo.getSessionKey(), wxLoginInfoVo.getIv());
        if(StringUtils.isEmpty(userInfoJson)){
            throw new BusinessException(ResultEnum.WEIXIN_USER_ANALYSE_FAIL);
        }
        WxLoginInfoAnalyze wxLoginInfo = JSONObject.parseObject(userInfoJson, WxLoginInfoAnalyze.class);
        log.info("解析的结果{}", JSONObject.toJSONString(wxLoginInfo));
        WebUserInfoDto webUserInfoDto = new WebUserInfoDto();
        webUserInfoDto.setOpenId(wxLoginInfoVo.getOpenId());
        webUserInfoDto.setPhone(wxLoginInfo.getPurePhoneNumber());
        webUserInfoDto.setZone(wxLoginInfo.getCountryCode());
        return AjaxResult.success(webUserInfoDto);
    }

    public static String decryptUserInfo(String sSrc, String encodingFormat, String sKey, String ivParameter) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            return new String(original, encodingFormat);
        } catch (Exception ex) {
            log.error("message异常{}", ex.getMessage());
            ex.printStackTrace();
            return null;
        }
    }

}
